import { Provide } from '@midwayjs/core'
import { InjectEntityModel } from '@midwayjs/typegoose'
import { ReturnModelType } from '@typegoose/typegoose'
import { Table } from '../../entity/examples/table.js'
import { randomUUID } from 'node:crypto'

@Provide()
export class TableService {
  @InjectEntityModel(Table)
  tableModel: ReturnModelType<typeof Table>

  async insertMany(tables: any[]): Promise<any[]> {
    for (const item of tables) {
      const table: any = item
      if (!table.id) table.id = randomUUID()
    }
    return this.tableModel.insertMany(tables)
  }

  async find(query: Record<string, any>): Promise<any> {
    const { currentPage, pageSize } = query
    const options: any = {
      sort: { _id: -1 }
    }

    if (currentPage) {
      options.skip = (currentPage - 1) * pageSize
      delete query.currentPage
    }

    if (pageSize) {
      options.limit = +pageSize
      delete query.pageSize
    }

    const total = await this.tableModel.countDocuments(query).exec()
    const data = await this.tableModel.find(query, null, options).exec()

    return {
      total: total,
      data: data
    }
  }

  async deleteOne(data: any): Promise<any> {
    return await this.tableModel.deleteOne(data).exec()
  }
}
